package com.abc.robot01.vivemodel

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abc.robot01.activity.RenderActivity
import com.abc.robot01.activity.toJSONString
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.retrofit.bean.HouseType
import com.abc.robot01.retrofit.bean.HouseType2
import com.abc.robot01.retrofit.bean.RenderQueueData
import com.abc.robot01.retrofit.bean.SkyBoxData
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import java.math.BigDecimal
import java.math.RoundingMode
import java.text.SimpleDateFormat
import java.time.LocalTime
import java.util.Date
import java.util.Locale


class RenderViewModel : ViewModel() {

    companion object {
        private const val TAG = "RenderViewModel"
    }

    val amount = mutableStateOf("0.0")
    val started = mutableStateOf(false)

    //支付方式 1 帐户支付  2:(微信)扫码支付
    val paymentMethod = mutableStateOf(1)

    // Mutable States
    val selectedOption = mutableStateOf("日间渲染")
    val selectedIndex = mutableStateOf(0)
    val customerName = mutableStateOf("")
    val customerPhone = mutableStateOf("")
    val housePlansDataId = mutableStateOf("")
    val housePlansId = mutableStateOf("")
    val taskId = mutableStateOf("")
    val more = mutableStateOf("11")

    /**
     * 总数量
     */
    val totalQuantity = mutableStateOf("1")

    val day = mutableStateOf(false)

    /**
     * 总金额
     */
    val totalAmount = mutableStateOf("0.00")

    val designPackageId = mutableStateOf("")

    // 获取当前时间戳，并格式化为 "yyyyMMddHHmmss" 格式
    val timestamp = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(Date())

    // 将格式化后的时间戳作为初始值
    val houseName = mutableStateOf(timestamp)

    // Lists
    var houseTypeList = mutableStateOf(emptyList<HouseType2>())

    private val _designerList = MutableStateFlow<List<HouseType>>(emptyList())
    val designerList: StateFlow<List<HouseType>> = _designerList

    //价格配置
    private val _modeList = MutableStateFlow<List<RenderQueueData>>(emptyList())
    val modeList: StateFlow<List<RenderQueueData>> = _modeList

    val selectedSkyBoxName = mutableStateOf("")

    private val _skyBoxList = MutableStateFlow<List<SkyBoxData>>(emptyList())
    val skyBoxList: StateFlow<List<SkyBoxData>> = _skyBoxList

    fun getTotal(houseTypeList: List<HouseType2>): String {
        var sum = BigDecimal("0.00")
        houseTypeList.filter { it.selected }.forEach {
            val value = BigDecimal(it.renderPrice.toString())
            sum = sum.add(value)
        }
        Log.e(RenderActivity.TAG, "当前选择的是:" + selectedOption.value)

        modeList.value.forEach {
            Log.e(RenderActivity.TAG, "价格系数: " + it)
        }

        val s = modeList.value.find {
            it.name == selectedOption.value
        }?.ratio ?: 1.0
        Log.e(RenderActivity.TAG, "当前选择的价格系数是:" + s)

        sum = sum.multiply(BigDecimal.valueOf(s))

        // 四舍五入到小数点后两位
        val roundedValue = sum.setScale(2, RoundingMode.HALF_UP)

        Log.e(RenderActivity.TAG, "总费用: " + roundedValue)

        return roundedValue.toString()
    }

    // Submitting logic to calculate fees
    fun submit() {
        modeList.value.find { it.name == selectedOption.value }?.let { renderConfig ->
            Log.e(TAG, "Rendering price config: ${renderConfig.name}, ratio: ${renderConfig.ratio}")
            totalAmount.value = getTotal(houseTypeList.value)
        }
    }

    fun load() {
        viewModelScope.launch {

//               获取公司钱包余额
            RetrofitService.instance.getPurseAmount(Robot.accessToken, Robot.companyId).also {
                amount.value = it.data.toString()
            }

            val s = RetrofitService.instance.designRenderSkyBox(Robot.accessToken)
            _skyBoxList.value = s.data
            selectedSkyBoxName.value = s.data.component1().name
            Log.e(TAG, "获取天空盒配置: " + s.toJSONString())


            val a1 =
                RetrofitService.instance.designRenderPriceConfig(accessToken = Robot.accessToken)
            Log.e(TAG, "获取渲染价格配置: " + a1)
            a1.data.forEach {
                Log.e(TAG, "获取渲染价格配置: " + it)
            }
            _modeList.value = a1.data

            Log.e(TAG, "housePlansDataId.value:" + housePlansDataId.value)
            Log.e(TAG, "designPackageId.value:" + designPackageId.value)
            val res = RetrofitService.instance.getRenderRooms(
                accessToken = Robot.accessToken,
                housePlansDataId = housePlansDataId.value,
                designPackageId = designPackageId.value
            )
            if (res.code == 200) {
                Log.e(TAG, "渲染房间: " + res)
                res.data.forEach {
                    Log.e(TAG, "空间: " + it)
                }

                houseTypeList.value = res.data.map {
                    HouseType2(id = it.roomId, name = it.roomTypeName, renderPrice = it.renderPrice)
                }
                totalQuantity.value = houseTypeList.value.size.toString()
                totalAmount.value = getTotal(houseTypeList.value)
            }
            RetrofitService.instance.countWaitRenderConfig(Robot.accessToken).also {
                Log.e(TAG, "获取待渲染的任务数: " + it)
                if (it.code == 200) {
                    more.value = it.data.toString()
                }
            }

        }
    }

    fun isWithinDaytime(): Boolean {
        // 定义白天的时间范围
        val startTime = LocalTime.of(8, 30)  // 08:30
        val endTime = LocalTime.of(22, 59, 59)  // 22:59:59

        // 获取当前时间
        val now = LocalTime.now()

        // 判断当前时间是否在范围内
        return now.isAfter(startTime) && now.isBefore(endTime).also {
            day.value =  it
        }
    }
}
